<?php

    if ( !defined ( 'BASEPATH' ) )
        exit ( 'No direct script access allowed' );

    /**
     * Controls data flow from website and rest services
     *
     * NOTES:
     *
     * Variables:
     * $session  is created in "template" library - used in view's
     */
    class Booking extends CI_Controller {

        private $data;
        private $filters_count = array (
            'filter_price' => array (),
            'filter_class' => array (
                'class-1' => 0,
                'class-2' => 0,
                'class-3' => 0,
                'class-4' => 0,
                'class-5' => 0,
                'class-0' => 0
            ),
            'hotel_type' => array (
                'hotel' => 0,
                'apartment' => 0,
                'villa' => 0
            ),
            'filter_facilities' => array ()
        );

        function __construct ()
        {

            parent::__construct ();

            $this->load->library ( 'rest', array (
                'server' => REST_URL,
                'http_user' => 'cipa',
                'http_pass' => 'booking',
                'http_auth' => 'basic' // or 'digest' 
            ) );

            $this->data['host_url'] = HOST_URL;

            $this->lang->load ( 'common' );

            define ( 'DEBUG_SESSION', FALSE );
        }

        public function index ()
        {

            //$this->session->sess_destroy();
            if ( $this->session->userdata ( 'my_data' ) ):
                $this->session->set_userdata ( 'my_data', NULL );
            endif;

            $this->data['title'] = "Welcome";

            $home_input = array ('popular', 'visited', 'specialHotels', 'specialDests', 'recommended');

            $combined = $this->rest->post ( 'home', array ('input' => $home_input) );
            if ( $combined ):
                $this->data['destinations'] = $combined->popular;
                $this->data['most_viewed'] = $combined->visited;
                $this->data['specialHotels'] = $combined->specialHotels;
                $this->data['specialDests'] = $combined->specialDests;
                $this->data['we_recommend'] = $combined->recommended;
            endif;

            //$this->firephp->log ( $this->data['specialHotels'] );

            if ( isset ( $_GET ) )
            {
                $this->session->set_userdata ( 'my_data', $_GET );
            }
            $this->_debug_session ();
            $this->template->load ( 'home/home', $this->data );
        }

        /**
         *
         * $_GET
         *
         * dest_hot              :String
         * check_in              :Date
         * check_out             :Date
         * nr_adults             :Integer
         * nr_childrens          :Integer
         * ages                  :Array
         * non_specific_dates    :Boolean
         *
         */
        public function search ()
        {

            //$this->lang->load('common');
            //$this->firephp->log($this->lang->lang());

            $this->data['title'] = "Hotels list";

            $_GET['dest_hot'] = trim ( $_GET['dest_hot'] );

            // ako je setovan page_num to znaci da je klinkuto na neki od linkova - prev -next
            // ako nije znaci da je kliknuto na filtere ili prvi put ucitan search ili popular te treba resetovati paginaciju
            // to radimo tako sto provjerimo u funkciji za paginaciju $this->data['page_num'];
            if ( isset ( $_GET['page_num'] ) )
            {
                $this->data['page_num'] = $_GET['page_num'];
                unset ( $_GET['page_num'] );
            }


            // no dates specified, just serach object based on destination/hotel
            if ( isset ( $_GET['non_specific_dates'] ) ):

                $rest_data = array (
                    "dest_hot" => $_GET['dest_hot'],
                    "lang" => $this->lang->lang ()
                );

                //$this->firephp->log($rest_data);

                if ( isset ( $_GET['sort_by'] ) ):
                    $rest_data['sort_by'] = $_GET['sort_by'];

                endif;

                cleanup_GET_array ();
                $this->data['objects'] = $this->rest->post ( "searchPreview", $rest_data );

//                $this->firephp->log ( $this->data['objects'] );
                //return;



                $this->session->set_userdata ( 'my_data', $_GET );
                $this->_debug_session ();


                $this->_do_find_facilities_filters ( $this->data['objects'] );
                $this->_do_filters_count ( $this->data['objects'] );
                $this->data['filters_count'] = $this->filters_count;
                $this->data['objects'] = $this->_do_filter ( $this->data['objects'] );
                // pagination
                // prije paginationa potrebno je prebrojati koliko objekata ima u cijelom nizu koji su vratili restfull
                // servisi nakon izvrsavanja filtera
                $this->data['total_objects_count'] = count ( $this->data['objects'] );
                $this->data['objects'] = $this->_do_pagination ( $this->data['objects'] );

                // TODO dio za currency swap
                if ( $this->setCurrencyOptions () )
                {
                    $this->swapCurrency ( $this->data['objects'], '' );
                }

                //$this->firephp->log($this->data['object']);



                $this->template->load ( 'booking/hotels-list', $this->data );

                // remove checkin, checkout, set nradults, nrchildrens
                //$this->_debug_session();
                //$this->firephp->log($this->data['objects']);
                return;

            endif; // end no specific dates
            //
            // dates are submited, preform search
            cleanup_GET_array ();

            $rest_data = $_GET;
            $rest_data['lang'] = $this->lang->lang ();

//            $this->firephp->log ( $rest_data );

            $this->data['objects'] = $this->rest->post ( "search", $rest_data );

            //$this->firephp->log($this->data['objects']);
            //$this->firephp->log($_GET);
            //$this->firephp->log($this->data['objects']);
            $this->session->set_userdata ( 'my_data', $_GET );

            //$this->firephp->log($this->data['objects']);

            $this->_do_find_facilities_filters ( $this->data['objects'] );
            $this->_do_filters_count ( $this->data['objects'] );

            $this->data['filters_count'] = $this->filters_count;
            $this->data['objects'] = $this->_do_filter ( $this->data['objects'] );

            // pagination
            $this->data['total_objects_count'] = count ( $this->data['objects'] );
            $this->data['objects'] = $this->_do_pagination ( $this->data['objects'] );

            // TODO dio za currency swap
            //$this->firephp->log($_GET);

            if ( $this->setCurrencyOptions () )
            {
                $this->swapCurrency ( $this->data['objects'], '' );
            }



            $this->_debug_session ();
            $this->template->load ( 'booking/hotels-list', $this->data );
        }

        /**
         * $_GET
         *
         * dest_hot              :String
         * object_type           :String
         */
        public function popular ()
        {

            $this->data['title'] = "Hotels list";

            $_GET['dest_hot'] = trim ( $_GET['dest_hot'] );


            // unsetovanje za paginaciju

            if ( isset ( $_GET['page_num'] ) )
            {
                $this->data['page_num'] = $_GET['page_num'];
                unset ( $_GET['page_num'] );
            }




            $rest_data = array (
                "dest_hot" => $_GET['dest_hot'],
                "lang" => $this->lang->lang ()
            );

            if ( isset ( $_GET['object_type'] ) ):
                $rest_data['object_type'] = $_GET['object_type'];
            endif;

            if ( isset ( $_GET['sort_by'] ) ):
                $rest_data['sort_by'] = $_GET['sort_by'];

            endif;

            $this->data['objects'] = $this->rest->post ( "searchPreview", $rest_data );

            //$this->firephp->log($this->data['objects']);

            $this->session->set_userdata ( 'my_data', $_GET );

            $this->_do_find_facilities_filters ( $this->data['objects'] );
            $this->_do_filters_count ( $this->data['objects'] );
            $this->data['filters_count'] = $this->filters_count;
            $this->data['objects'] = $this->_do_filter ( $this->data['objects'] );

            // pagination
            $this->data['total_objects_count'] = count ( $this->data['objects'] );
            $this->data['objects'] = $this->_do_pagination ( $this->data['objects'] );


            $this->_debug_session ();
            $this->template->load ( 'booking/hotels-list', $this->data );
        }

        /**
         *
         * $_GET
         *
         * dest_hot              :String
         * check_in              :Date
         * check_out             :Date
         * nr_adults             :Integer
         * nr_childrens          :Integer
         * ages                  :Array
         * non_specific_dates    :Boolean
         * object_type           :String
         * sort_by               :String
         *
         */
        public function sort_hotels ()
        {

            // We do check if my_data['check_in'] is set in session
            // if so, we sort from search, if not, we sort from serch_preview
            $my_data = $this->session->userdata ( 'my_data' );

            if ( isset ( $my_data['check_in'] ) )
            {
                redirect ( base_url ( 'search?' . http_build_query ( $_GET ) ) );
            }
            else
            {
                redirect ( base_url ( 'popular?' . http_build_query ( $_GET ) ) );
            }
        }

        /**
         *
         * $_GET
         *
         * hotel_id              :Integer
         *
         */
        public function details_preview ()
        {

            if ( isset ( $_GET['dest_hot'] ) )
                $_GET['dest_hot'] = trim ( $_GET['dest_hot'] );


            $rest_data = array (
                "hotel_id" => $_GET['hotel_id'],
                "lang" => $this->lang->lang ()
            );


            $this->data['object'] = $this->rest->post ( "detailsPreview", $rest_data );
            $this->data['title'] = $_GET['dest_hot'] = $this->data['object']->object_name;
            $this->session->set_userdata ( 'my_data', $_GET );

            //$this->firephp->log($this->data['object']);
            $this->_debug_session ();
            $this->template->load ( 'booking/hotel-details', $this->data );
        }

        /**
         *
         * $_GET
         *
         * dest_hot              :String
         * check_in              :Date
         * check_out             :Date
         * nr_adults             :Integer
         * nr_childrens          :Integer
         * ages                  :Array
         * non_specific_dates    :Boolean
         *
         */
        public function details ()
        {

            // dates are submited, preform search
            //$this->firephp->log($this->lang->lang());

            cleanup_GET_array ();

            //

            $rest_data = $_GET;
            $rest_data['lang'] = $this->lang->lang ();

            $this->data['object'] = $this->rest->post ( "details", $rest_data );
            $this->data['title'] = $_GET['dest_hot'] = $this->data['object']->object_name;
            $this->session->set_userdata ( 'my_data', $_GET );

            //$this->firephp->log($this->data['object']);



            if ( $this->setCurrencyOptions () )
            {
                $this->swapCurrency ( $this->data['object'], '' );
            }
            //$this->firephp->log($this->data['object']);

            $this->_debug_session ();
            $this->template->load ( 'booking/hotel-details', $this->data );
        }

        public function reservation_cancellation ()
        {

            $this->data['title'] = "Reservation Cancellation";
            $this->data['reservation_ID'] = $this->input->get ( 'reservation_ID' );
            $this->_debug_session ();
            $this->template->load ( 'reservation/cancel', $this->data );
        }

        public function cancellation_confirmation ()
        {

            $this->data['title'] = "Cancellation Confirmation";
            $this->data['reservation_ID'] = $this->input->get ( 'reservation_ID' );
            $result = $this->rest->post ( "reservation_cancellation", array ('reservation_ID' => $this->data['reservation_ID']) );
            $this->_debug_session ();
            $this->template->load ( 'reservation/cancellation_confirmation', $this->data );
        }

//        public function hotel_details_map($object_ID)
//        {
//            //$object_ID=$this->security->xss_clean($object_ID);
//
//            $rest_data=array(
//                "hotel_id" => $object_ID
//            );
//
//            $data['hotel']=$this->rest->post("details_preview", $rest_data);
//
//            //$this->firephp->log($data['hotel']);
//
//            $html=$this->load->view('layouts/google_object', $data, TRUE);
//            $this->_debug_session();
//            echo json_encode(
//                    array('action' => true,
//                        'html' => $html
//            ));
//
//        }

        /**
         *
         * $_GET
         *
         * dest_hot              :String
         * check_in              :Date
         * check_out             :Date
         * nr_adults             :Integer
         * nr_childrens          :Integer
         * ages                  :Array
         * non_specific_dates    :Boolean
         *
         */
        public function search_google_object ( $object_ID )
        {

            $my_data = $this->session->userdata ( 'my_data' );

            if ( !$my_data )
            {
                $this->_debug_session ();
                echo json_encode (
                        array ('action' => false,
                            'msg' => 'session_expired'
                ) );
                return;
            }
            //$this->firephp->log($my_data);

            $my_data['hotel_id'] = $object_ID;

            //$this->firephp->log($my_data);

            $data['hotel'] = $this->rest->post ( "details", $my_data );

            //$this->firephp->log("HOTEL DATA BEFORE SWAP");
            //$this->firephp->log($data['hotel']);

            if ( $this->setCurrencyOptions () )
            {
                $this->swapCurrency ( $data['hotel'], 'google_object' );
            }

            //$this->firephp->log("HOTEL DATA AFTER SWAP");
            //$this->firephp->log($data['hotel']);

            $data['session'] = $this->session->userdata ( 'my_data' );

            $html = $this->load->view ( 'layouts/google_object', $data, TRUE );

            //echo $html;

            $this->_debug_session ();
            echo json_encode (
                    array ('action' => true,
                        'html' => $html
            ) );
        }

        public function search_preview_google_object ( $object_ID )
        {

            $my_data = $this->session->userdata ( 'my_data' );

            if ( !$my_data )
            {
                $this->_debug_session ();
                echo json_encode (
                        array ('action' => false,
                            'msg' => 'session_expired'
                ) );
                return;
            }

            $rest_data = array (
                "dest_hot" => $my_data['dest_hot'],
                "hotel_id" => $object_ID
            );

            $data['hotel'] = $this->rest->post ( "detailsPreview", $rest_data );



            $data['session'] = $this->session->userdata ( 'my_data' );


            //$this->firephp->log($data);
            $html = $this->load->view ( 'layouts/google_object', $data, TRUE );

            //echo $html;

            $this->_debug_session ();
            echo json_encode (
                    array ('action' => true,
                        'html' => $html
            ) );
        }

        private function _debug_session ()
        {
            if ( DEBUG_SESSION ):

                $data = $this->session->userdata ( 'my_data' );

                if ( !$data )
                {
                    $this->firephp->log ( 'my_data is: empty' );
                }
                else
                {
                    $this->firephp->log ( 'my_data is:' );
                    $this->firephp->log ( $this->session->userdata ( 'my_data' ) );
                }

            endif;
        }

        private function _do_filter ( $objects )
        {

            $filters = array (
                'filter_price' => 'rooms',
                'filter_facilities' => 'facilities',
                'filter_class' => 'object_number_of_stars',
                'hoteltype' => 'object_type_type'
            );

            // check if ajax filters
            if ( isset ( $_GET['ajax_filter'] ) ):

                //
                // go troug each filter type
                foreach ( $filters as $filter => $object_field ):

                    //$this->firephp->log($filter);
                    // check if that type is submites
                    if ( isset ( $_GET[$filter] ) ):



                        //$this->firephp->log($filter);

                        switch ( $filter ):

                            case 'filter_class':

                                // do something
                                //$this->firephp->log($_GET[$filter]);

                                $cnt = count ( $objects );

                                for ( $i = 0; $i < $cnt; $i++ ):

                                    $to_compare_stars = $objects[$i]->object_number_of_stars;
                                    if ( $to_compare_stars == "" )
                                        $to_compare_stars = 0;

                                    if ( in_array ( 'class-' . $to_compare_stars, $_GET[$filter] ) )
                                    {
                                        //$this->firephp->log($objects[$i]->object_type_type.' is included in filters');
                                    }
                                    else
                                    {
                                        //$this->firephp->log($objects[$i]->object_type_type.' is not included in filters');
                                        unset ( $objects[$i] );
                                    }



                                endfor;

                                $objects = array_values ( $objects );

                                //$this->firephp->log('Count afther filter_class:'.count($objects));

                                break;

                            case 'hoteltype':

                                // do something
                                //$this->firephp->log($_GET[$filter]);

                                $cnt = count ( $objects );

                                for ( $i = 0; $i < $cnt; $i++ ):

                                    if ( in_array ( $objects[$i]->object_type_type, $_GET[$filter] ) )
                                    {
                                        //$this->firephp->log($objects[$i]->object_type_type.' is included in filters');
                                    }
                                    else
                                    {
                                        //$this->firephp->log($objects[$i]->object_type_type.' is not included in filters');
                                        unset ( $objects[$i] );
                                    }



                                endfor;

                                $objects = array_values ( $objects );

                                //$this->firephp->log('Count afther hoteltype:'.count($objects));

                                break;

                            case 'filter_facilities':

                                $cnt = count ( $objects );
                                for ( $i = 0; $i < $cnt; $i++ ):

                                    $objects[$i]->facility = array ();

                                    // do create clean facility array
                                    foreach ( $objects[$i]->facilities as $group ):

                                        if ( !empty ( $group ) ):

                                            foreach ( $group as $key => $attribute ):

                                                //$this->firephp->log($key);
                                                //$attribute=trim($attribute);

                                                $objects[$i]->facility[$key] = 1;

                                            endforeach;

                                        endif;

                                    endforeach;

                                    // if empty facilities, nothing to search, do remove object
                                    if ( empty ( $objects[$i]->facility ) )
                                        unset ( $objects[$i] );

                                endfor;

                                $objects = array_values ( $objects );

                                // do filter
                                $cnt = count ( $objects );
                                for ( $i = 0; $i < $cnt; $i++ ):

                                    $found = 1;


                                    foreach ( $_GET[$filter] as $key => $value ):

                                        //$this->firephp->log($objects[$i]->facility);

                                        if ( !array_key_exists ( $value, $objects[$i]->facility ) )
                                        {
                                            $found = 0;
                                            //$this->firephp->log('found:'.$value);
                                        }

                                    endforeach;


                                    if ( $found == 0 )
                                        unset ( $objects[$i] );

                                endfor;

                                $objects = array_values ( $objects );



                                break;

                            case 'filter_price':

                                //$this->firephp->log('filter_price');
                                // do something
                                //get filters

                                $filters = array ();

                                foreach ( $_GET[$filter] as $filter ):

                                    $pieces = explode ( '_', $filter );

                                    array_push ( $filters, array (
                                        'from' => $pieces[1],
                                        'to' => $pieces[2] == -1 ? 999999 : $pieces[2],
                                    ) );

                                endforeach;

                                //$this->firephp->log($filters);
                                // go troug each filter and do remove rooms that do not fit between

                                foreach ( $filters as $value ):

                                    //$this->firephp->log($value['from'].' - '.$value['to']);

                                    $cnt = count ( $objects );

                                    for ( $i = 0; $i < $cnt; $i++ ): // go troug each object

                                        $rooms = $objects[$i]->rooms;

                                        $cnt_rooms = count ( $rooms );
                                        $found = 0;

                                        for ( $j = 0; $j < $cnt_rooms; $j++ ): // go troug each room

                                            $price = $rooms[$j]->selling_total;

                                            if ( $price >= $value['from'] && $price < $value['to'] ):
                                                //$this->firephp->log("Price ".$price.' is between '.$value['from'].' and '.$value['to'].'. Hotel '.$objects[$i]->object_name);
                                                $found = 1;
                                            endif;
                                            {
                                                
                                            }

                                        endfor;

                                        if ( $found == 0 ):
                                            unset ( $objects[$i] );

                                        endif;

                                    endfor;

                                    $objects = array_values ( $objects );


                                endforeach;

                                break;

                        endswitch;




                    endif;



                endforeach;


            endif;

            //$this->firephp->log($objects);
            return $objects;
        }

        private function _do_filters_count ( $objects )
        {
            foreach ( $objects as $hotel ):

                // Star rating
                //$this->firephp->log($hotel->object_number_of_stars);
                if ( $hotel->object_number_of_stars == "" )
                {
                    $this->filters_count['filter_class']['class-0']++;
                }
                else
                {
                    $this->filters_count['filter_class']['class-' . ( int ) $hotel->object_number_of_stars]++;
                }
                //filter_class
                // Hotel Type

                $this->filters_count['hotel_type'][$hotel->object_type_type]++;

            endforeach;
        }

        private function _do_find_facilities_filters ( $objects )
        {


            $filter_facilities = array ();

            foreach ( $objects as $hotel ):

                $facilities = $hotel->facilities;

                // Ovdje cemo kreirati niz na nivou objekta za jedinstvenu provjeru atributa
                $unique_attribute = array ();


                foreach ( $facilities as $group ):
                    if ( !empty ( $group ) )
                    {
                        foreach ( $group as $key => $attribute ):

                            //$this->firephp->log($key);
                            //$attribute=trim($attribute);

                            if ( !in_array ( $key, $unique_attribute ) ):
                                $unique_attribute[].=$key;




                                if ( isset ( $filter_facilities[$key] ) )
                                {
                                    $filter_facilities[$key]->cnt++;
                                }
                                else
                                {
                                    $filterSTD = new stdClass;
                                    $filterSTD->title = $attribute;
                                    $filterSTD->cnt = 1;
                                    //$filter_facilities[$key]=1;
                                    $filter_facilities[$key] = $filterSTD;
                                }



                            endif;



                        endforeach;
                    }
                endforeach;

            endforeach;

            $final_array = $filter_facilities;

            $filter_facilities = $this->_sort_me ( $filter_facilities );



            if ( count ( $filter_facilities ) > 17 )
            {
                array_splice ( $filter_facilities, 17 );
            }

            // Ovo sluzi za sminku
            foreach ( $final_array as $attr => $key ):

                if ( !array_key_exists ( $attr, $filter_facilities ) ):
                    unset ( $final_array[$attr] );
                endif;
            //$i++;
            endforeach;

            //return $final_array;
            $this->filters_count['filter_facilities'] = $final_array;
        }

        private function _sort_me ( $facilities )
        {
            $sorted = array ();

            $cnt = count ( $facilities );
            $i = 0;
            foreach ( $facilities as $key1 => $std1 ):

                $sorted[$i] = $std1;
                $sorted[$i]->key = $key1;

                $j = 0;
                foreach ( $facilities as $key2 => $std2 ):

                    if ( $j > $i ):
                        if ( $std2->cnt > $sorted[$i]->cnt ):
                            $sorted[$i] = $std2;
                            $sorted[$i]->key = $key2;
                        endif;
                    endif;

                    $j++;

                endforeach;

                $i++;

            endforeach;

            $cnt2 = count ( $sorted );
            $final_sorted = array ();

            // Mama mia
            for ( $i = 0; $i < $cnt2; $i++ ):

                $final_sorted[$sorted[$i]->key] = $facilities[$sorted[$i]->key];

            endfor;

            return $final_sorted;
        }

        public function submit_review ()
        {

            $rest_data = $_GET;

            $success = $this->rest->post ( "submit_review", $rest_data );

            echo json_encode ( array (
                'success' => $success
            ) );
        }

        public function terms_and_conditions ()
        {

            $this->data['title'] = "Terms and conditions";

            $rest_data = array (
                "hotel_id" => $this->input->get ( 'hotel_id' ),
                "room_id" => $this->input->get ( 'room_id' ),
                "lang" => $this->lang->lang ()
            );

            $this->data['terms_conditions'] = $this->rest->post ( "termsConditions", $rest_data );

//            $this->firephp->log ( $this->data['terms_conditions'] );


            $this->template->set_view ( 'terms_conditions' );
            $this->template->load ( 'terms_conditions/conditions', $this->data );
        }

        public function general_terms ()
        {

            $this->data['title'] = "Terms and conditions";
            $this->template->set_view ( 'terms_conditions' );
            $this->template->load ( 'terms_conditions/terms', $this->data );
        }

        public function get_currency ( $from, $to, $amount )
        {

            $this->load->library ( 'foreign_exchange', array ('base' => $from, 'foreign' => $to) );

            //echo "<p>$amount $from is ".$this->fmtMoney($this->foreign_exchange->toForeign($amount))." $to</p>";
            return $this->fmtMoney ( $this->foreign_exchange->toForeign ( $amount ) );
        }

        // This function formats a value with 2 decimal places.
        function fmtMoney ( $amount )
        {
            return number_format ( $amount, 2 );
        }

        function setCurrencyOptions ()
        {
            // check if change_currency is set and if it is get currency rate store it in session and return
            // true / false if there's no need for currency swap

            $curSign = '&#128;';
            $data = $this->session->userdata ( 'my_data' );

            // TODO ovdje ne moze samo $_GET jer se google objekat ne poziva kroz GET vec pomocu ajaxa pa zato nemamo
            // get vec moramo provjeriti sesiju !

            if ( isset ( $_GET['change_currency'] ) && isset ( $_GET['currency'] ) )
            {
                $data['exchange_rate'] = $this->get_currency ( 'EUR', $_GET['currency'], 1 );


                switch ( $_GET['currency'] )
                {
                    case 'EUR':
                        $curSign = '&#128;';
                        break;
                    case 'RUB':
                        $curSign = 'RUB';
                        break;
                    case 'USD':
                        $curSign = '$';
                        break;
                }
                $data['currency_sign'] = $curSign;

                $this->session->set_userdata ( 'my_data', $data );

                //$this->firephp->log('SETTING CURRENCY OPTIONS');
                $this->_debug_session ();

                return TRUE;
            }
            elseif ( isset ( $this->session->userdata['my_data']['change_currency'] ) )
            {
                $data['exchange_rate'] = $this->get_currency ( 'EUR', $this->session->userdata['my_data']['currency'], 1 );


                switch ( $this->session->userdata['my_data']['currency'] )
                {
                    case 'EUR':
                        $curSign = '&#128;';
                        break;
                    case 'RUB':
                        $curSign = 'RUB';
                        break;
                    case 'USD':
                        $curSign = '$';
                        break;
                }
                $data['currency_sign'] = $curSign;

                $this->session->set_userdata ( 'my_data', $data );

                //$this->firephp->log('SETTING CURRENCY OPTIONS FROM SESSION');
                $this->_debug_session ();

                return TRUE;
            }

            $data['currency_sign'] = $curSign;
            $this->session->set_userdata ( 'my_data', $data );
            return FALSE;
        }

        function swapCurrency ( $objects, $callingmethod )
        {
            $data = $this->session->userdata ( 'mydata' );
            // loop through objects, find selling total and swap selling total with new price

            if ( gettype ( $objects ) == 'array' )
            {
                for ( $j = 0; $j < count ( $objects ); $j++ )
                {
                    foreach ( $objects[$j] as $key => $value )
                    {

                        //$this->firephp->log('u petlji 1');
                        //$this->firephp->log($key);
                        if ( $key == 'rooms' )
                        {
                            //$this->firephp->log('u petlji 2');

                            $rooms = $value;

                            //$this->firephp->log($rooms);
                            $i = 0;
                            for ( $i = 0; $i < count ( $objects[$j]->rooms ); $i++ )
                            {

                                //$this->firephp->log('U SOBI !');
                                //$ds = $objects->rooms;
                                $amm = $objects[$j]->rooms[$i]->selling_total;

                                //$this->firephp->log('SELLING TOTAL = ' . $amm);

                                $new_selling_total = number_format ( $objects[$j]->rooms[$i]->selling_total * $this->session->userdata['my_data']['exchange_rate'] );
                                $objects[$j]->rooms[$i]->selling_total = $new_selling_total;

                                //$this->firephp->log($data['exchange_rate']);
                                //$this->firephp->log($objects);
                            }
                        }
                    }
                }
            }
            else
            {
                foreach ( $objects as $key => $value )
                {

                    //$this->firephp->log('u petlji 1');
                    //$this->firephp->log($key);
                    if ( $key == 'rooms' )
                    {
                        //$this->firephp->log('u petlji 2');

                        $rooms = $value;

                        //$this->firephp->log($rooms);
                        $i = 0;
                        for ( $i = 0; $i < count ( $objects->rooms ); $i++ )
                        {

                            //$this->firephp->log('U SOBI !');
                            //$ds = $objects->rooms;
                            $amm = $objects->rooms[$i]->selling_total;

                            //$this->firephp->log('SELLING TOTAL = ' . $amm);

                            $new_selling_total = number_format ( $objects->rooms[$i]->selling_total * $this->session->userdata['my_data']['exchange_rate'] );
                            $objects->rooms[$i]->selling_total = $new_selling_total;

                            //$this->firephp->log($data['exchange_rate']);
                            //$this->firephp->log($objects);
                        }
                    }
                }
            }
        }

        public function destinations_hotels_JSON ()
        {

            $rest_data = array (
                "name_startsWith" => $_GET['name_startsWith'],
                "plus_hotels" => TRUE,
                "lang" => $this->lang->lang ()
            );

            $items = $this->rest->post ( "destinationsHotelsAutocomplete", $rest_data );

            //echo JSON to page  
            $response = $_GET["callback"] . "(" . json_encode ( array ('items' => $items) ) . ")";

            echo $response;
        }

        public function subscribe ()
        {

            $rest_data = array (
                "email" => $_GET['subscribe_input']
            );

            $items = $this->rest->post ( "subscribe", $rest_data );

            echo json_encode ( array ('success' => TRUE) );
        }

        public function _do_pagination ( $object )
        {
            // calculate length of objects array
            // get required page
            // unset array objects from beginning to req_page*num_per_page and from req_page*num_per_page + num_per_page to end;

            $this->data['last_page'] = false;


            $num_pages = count ( $object );

            //$this->firephp->log($object);
            //$this->firephp->log("NUM OF OBJECTS " . $num_pages);

            $per_page = 9;

            // calculate number of pages
            $pages = ceil ( floatval ( $num_pages ) / floatval ( $per_page ) );

            //$this->firephp->log("NUM OF PAGES " . $pages);
            //$this->firephp->log("PAGE NUMBER " . intval($this->data['page_num']));
            // po default nema splitovanja

            $start = 0;


            if ( isset ( $this->data['page_num'] ) )
            {

                // ako je setovano znaci da treba prebaciti stranu...
                // uzimamo per_page elemenata
                $start = $per_page * $this->data['page_num'];

                if ( $pages == intval ( $this->data['page_num'] ) + 1 )
                {

                    // dosli smo do zadnje strane, setujemo $this->data['last_page']=true;
                    $this->data['last_page'] = true;
                }
            }
            elseif ( $pages == 1 || $pages == 0 )
            {
                // jedna je stranica ili nemamo rezultata uopste
                // ovdje ne moramo splitovati niz objekata jer svaki treba da se prikaze u prvoj strani
                $this->data['page_num'] = 0;
                $this->data['last_page'] = true;
            }
            else
            {
                $this->data['page_num'] = 0;
                $this->data['last_page'] = false;
                $start = 0;
            }

            //$this->firephp->log("PAGE NUMBER = " . intval($this->data['page_num']));
            //$this->firephp->log("LAST PAGE =  " . intval($this->data['last_page']));
            // unset array objects from beginning to req_page*num_per_page and from req_page*num_per_page + num_per_page to end;
            //$this->firephp->log("START: " . $start);

//            $this->firephp->log ( $object );
            $object = array_splice ( $object, $start, $per_page );

            return $object;
        }

    }

?>